package cn.jxufe.zhangyong.mysqldbapp;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private ListView lvUsers;
    private EditText etUser, etSecret;
    public static SQLiteDatabase myDB = null;
    private final static String MY_DB_NAME = "myuser.db";
    public  static String MY_TB_NAME = "userinfo";
    public final static String MY_TB_USER = "users";
    public  static String MY_FD_USER = "user";
    private final static String MY_FD_SECRET = "secret";
    public  static String MY_FD_PASSWD = "passwd";
    public static boolean logon = false;
    public static String[] userStr=new String[100];
    public String[] userS={"wh","mzj","cyj","syx"};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_sqldb);
        myInitGUI();
        if(logon==false){
            Intent intent = new Intent(MainActivity.this,LoginActivity.class);
            //前一个（MainActivity.this）是目前页面，后面一个是要跳转的下一个页面
            startActivity(intent);
        }
    }

    public void onDestroy() {
        super.onDestroy();
        myDB.close();
    }
    public void onResume() {
        super.onResume();
        if(logon==false){
            Intent intent = new Intent(MainActivity.this,LoginActivity.class);
            startActivity(intent);
        }
    }
    public void myInitGUI() {
        etUser = (EditText) findViewById(R.id.etuser);
        etSecret = (EditText) findViewById(R.id.etsecret);
        lvUsers = (ListView) findViewById(R.id.lvcont);
        lvUsers.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                TextView tv_usr = (TextView) arg1.findViewById(R.id.user_name);
                TextView tv_sec = (TextView) arg1.findViewById(R.id.user_secret);
                Cursor cursor = myDB.query(MY_TB_NAME,
                        null,//new String[]{"_id",MY_FD_USER,MY_FD_SECRET},
                        " user='" + tv_usr.getText().toString() + "'" +
                                " AND secret='" + tv_sec.getText().toString() + "'",
                        null, null, null, null);
                if (cursor != null) {
                    cursor.moveToFirst();
                    int loc = cursor.getColumnIndex(MY_FD_USER);
                    etUser.setText(cursor.getString(loc));
                    loc = cursor.getColumnIndex(MY_FD_SECRET);
                    etSecret.setText(cursor.getString(loc));
                }
            }
        });
        myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null);

        myDB.execSQL("CREATE TABLE IF NOT EXISTS " + MY_TB_NAME +
                "(_id INTEGER PRIMARY KEY, user TEXT,secret TEXT)");

        myDB.execSQL("CREATE TABLE IF NOT EXISTS " + MY_TB_USER +
                "(_id INTEGER PRIMARY KEY, user TEXT,passwd TEXT)");

        ContentValues cv = new ContentValues();
        System.arraycopy(userS, 0, userStr, 0, userS.length);
        for (String s:userStr) {
            if (s!=null){
                myDB.execSQL("CREATE TABLE IF NOT EXISTS " + s +
                        "(_id INTEGER PRIMARY KEY, user TEXT,secret TEXT)");
                cv.put(MY_FD_USER, s);
                cv.put(MY_FD_PASSWD, "1");
                myDB.insert(MY_TB_USER,null,cv);
            }

        }

        myDispRec();
    }

    public void myAddMD(View v) {
        if (etSecret.getText().toString().equals("")) {
        } else {
            ContentValues cv = new ContentValues();
            cv.put(MY_FD_USER, etUser.getText().toString());
            cv.put(MY_FD_SECRET, etSecret.getText().toString());
            myDB.insert(MY_TB_NAME, null, cv);
            etUser.setText("");
            etSecret.setText("");
            myDispRec();
        }
    }

    public void myDelMD(View v) {
        if (etSecret.getText().toString().equals("")) {
        } else {
            myDB.delete(MY_TB_NAME, " user='" + etUser.getText().toString() + "'" +
                    " AND secret='" + etSecret.getText().toString() + "'", null);
            myDispRec();
            etUser.setText("");
            etSecret.setText("");
        }
    }

    public void myDelallMD(View v) {
        new AlertDialog.Builder(this)
                .setTitle("删除所有密码")
                .setMessage("你确认删除吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // continue
                        myDB.delete(MY_TB_NAME, null, null);
                        etUser.setText("");
                        etSecret.setText("");
                        myDispRec();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // do nothing
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();

    }

    public void myDispMD(View v) {
        myDispRec();
    }

    private void myDispRec() {
        Cursor cursor = myDB.query(MY_TB_NAME,
                null,//new String[]{"_id",MY_FD_USER,MY_FD_SECRET},
                null, null, null, null, "_id");
        ListAdapter listAdapter = new SimpleCursorAdapter(this,
                R.layout.userlist, cursor,
                new String[]{MY_FD_USER, MY_FD_SECRET},
                new int[]{R.id.user_name, R.id.user_secret},
                CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        lvUsers.setAdapter(listAdapter);
    }

    public void mySwitch(View v){
        if(logon==true){
            logon=false;
            Intent intent = new Intent(MainActivity.this,LoginActivity.class);
            startActivity(intent);
        }
    }


}
